<template>
  <div class="signatureTemplateManageTemp">
    <div class="config">
      <el-collapse v-model="collapse">
        <el-collapse-item :name="1" title="基本信息">
          <el-form :disabled="dialogType==='view'" ref="formBase" :model="formDataBase" label-width="100px" size="small"
                   :rules="rules">
            <el-row>
              <el-col :span="12">
                <el-form-item label="中文名称" prop="nameCn">
                  <el-input v-model="formDataBase.nameCn"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="编码标识" prop="name">
                  <el-input v-model="formDataBase.name"></el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="12">
                <el-form-item label="英文名称">
                  <el-input v-model="formDataBase.nameEn"></el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="24">
                <el-form-item label="中文描述" prop="describeCn">
                  <el-input v-model="formDataBase.describeCn"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="英文描述">
                  <el-input v-model="formDataBase.describeEn"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-collapse-item>
        <el-collapse-item :name="2">
          <template slot="title">
            规则配置 &nbsp;
            <span style="font-size: 11px;color: #F56C6C">{{ errorMsg }}</span>
          </template>
          <el-form ref="form" :model="formData" label-width="100px" size="small" :rules="rules_">
            <el-row>
              <el-col :span="16">
                <el-form-item label="纸张大小">
                  <el-radio-group v-model="size" @change="checkCanvas">
                    <template v-for="item in specification">
                      <el-radio-button :label="item.name"></el-radio-button>
                    </template>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="16">
                <el-form-item label="模板" prop="filePath">
                  <el-upload
                      class="upload-demo"
                      action="#"
                      :disabled="dialogType==='view'"
                      accept=".pdf"
                      :on-change="handleChange"
                      :on-remove="handleRemove"
                      :auto-upload="false"
                      :limit="1"
                      :file-list="fileList">
                    <el-button size="small" type="primary" :disabled="dialogType==='view'">点击上传</el-button>
                    <div slot="tip" class="el-upload__tip">请上传pdf（仅一个文件）</div>
                  </el-upload>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">

                <el-table :data="canvasListAll[size]" border align="center"
                          :row-class-name="tableRowClassName">
                  <el-table-column label="中文名称" prop="name" width="180px">
                    <template slot-scope="{row}">
                      <el-input :disabled="dialogType==='view'" size="mini" v-model="row.name"></el-input>
                    </template>
                  </el-table-column>
                  <el-table-column label="编码" prop="code" width="180px">
                    <template slot-scope="{row}">
                      <el-input :disabled="dialogType==='view'" size="mini" v-model="row.code" @blur="blurCode(row)"></el-input>
                    </template>
                  </el-table-column>
                  <el-table-column label="X坐标" prop="x" width="120px">
                    <template slot-scope="{row}">
                      <el-input-number :disabled="dialogType==='view'" size="mini" :min="1" @change="refreshCanvas"
                                       v-model="row.x"></el-input-number>
                    </template>
                  </el-table-column>
                  <el-table-column label="Y坐标" prop="y" width="120px">
                    <template slot-scope="{row}">
                      <el-input-number :disabled="dialogType==='view'" size="mini" :min="1" @change="refreshCanvas"
                                       v-model="row.y"></el-input-number>
                    </template>
                  </el-table-column>
                  <el-table-column label="宽度" prop="width" width="120px">
                    <template slot-scope="{row}">
                      <el-input-number :disabled="dialogType==='view'" size="mini" :min="1" @change="refreshCanvas"
                                       v-model="row.width"></el-input-number>
                    </template>
                  </el-table-column>
                  <el-table-column label="高度" prop="height" width="120px">
                    <template slot-scope="{row}">
                      <el-input-number :disabled="dialogType==='view'" size="mini" :min="1" @change="refreshCanvas"
                                       v-model="row.height"></el-input-number>
                    </template>
                  </el-table-column>
                  <el-table-column label="自增方向" prop="autoDirection">
                    <template slot-scope="{row}">
                      <template v-if="row.hasDynamic === 1">-</template>
                      <template v-else>
                        <el-select :disabled="dialogType==='view'" size="mini" v-model="row.autoDirection">
                          <el-option value="top" label="上"></el-option>
                          <el-option value="bottom" label="下"></el-option>
                          <el-option value="left" label="左"></el-option>
                          <el-option value="right" label="右"></el-option>
                        </el-select>
                      </template>
                    </template>
                  </el-table-column>
                  <el-table-column label="每列/行个数" prop="transitionNumber" width="120px">
                    <template slot-scope="{row}">
                      <template v-if="row.hasDynamic === 1">-</template>
                      <template v-else>
                        <el-input-number :disabled="dialogType==='view'" size="mini" :min="1"
                                         v-model="row.transitionNumber"></el-input-number>
                      </template>
                    </template>
                  </el-table-column>
                  <el-table-column label="自增值(px)" prop="autoIncrement" width="120px">
                    <template slot-scope="{row}">
                      <template v-if="row.hasDynamic === 1">-</template>
                      <template v-else>
                        <el-input-number :disabled="dialogType==='view'" size="mini" :min="1"
                                         v-model="row.autoIncrement"></el-input-number>
                      </template>
                    </template>
                  </el-table-column>
                  <el-table-column align="center" label="类型" prop="type" width="80">
                    <template slot-scope="{row}">
                      {{ row.hasDynamic === 1 ? "固定坐标" : row.type === 'popAdd' ? "自增坐标" : "动态坐标" }}
                    </template>
                  </el-table-column>
                  <el-table-column fixed="right" label="动态" width="50">
                    <template slot-scope="{row}">
                      <el-switch :active-value="2"
                                 :inactive-value="1"
                                 width="30"
                                 :disabled="dialogType==='view'?true:row.type!=='popAdd'"
                                 @change="setAttr(row)"
                                 v-model="row.hasDynamic">
                      </el-switch>
                    </template>
                  </el-table-column>
                  <el-table-column fixed="right" align="center" label="操作" width="60px">
                    <template slot-scope="{row,$index}">
                      <el-button type="text" size="mini" :disabled="dialogType==='view'"
                                 @click="removeItem(row)">
                        删除
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </el-col>
            </el-row>
          </el-form>
        </el-collapse-item>
      </el-collapse>

    </div>
    <div class="pdf_view">
      <transition name="fade" tag="template">
        <code-canvas ref="cc"
                     :pdfLink="formData.filePath"
                     v-if="showPdf"
                     :disabled="dialogType==='view'?true:autoView"
                     :canvasList.sync="canvasListAll[size]"
                     :errorFun="errorFun"
                     :paperSize="sizeObj"
                     :addToAttr=' addToAttr'
                     @selectedItem="v=>this.selected=v">
        </code-canvas>
      </transition>
    </div>

    <div class="md-component-btns">
      <el-button size="medium" v-if="dialogType!=='view'" type="primary" @click="save">保存</el-button>
      <el-button size="medium" @click="$emit('removeThisTabs')">取消</el-button>
    </div>
  </div>
</template>

<script>
import CodeCanvas from "@/views/TestMenu/codeCanvas.vue";

import * as api from "@/api/signatureTemplateManage/index"
import {getDic} from "@/api/common"
import {getToken} from "@/util/auth";
import {request} from "axios";

export default {
  name: "signatureTemplateManageTemp",
  components: {CodeCanvas},
  data() {
    return {
      showPdf: true,

      collapse: [1, 2],

      specification: ["A3", "A4", "A5"],

      formData: {
        specification: "",
        filePath: ""
      },

      formDataBase: {
        name: "",
        nameCn: "",
        nameEn: "",
        describeCn: "",
        describeEn: "",
      },
      rules: {
        nameCn: [{required: true, trigger: 'blur', message: "请输入中文名称"}],
        describeCn: [{required: true, trigger: 'blur', message: "请输入中文描述"}],
        name: [{
          required: true,
          trigger: 'blur',
          message: "请输入编码标识"
        }, {pattern: '^[A-Za-z][A-Za-z0-9_]{1,29}$', message: '请输入正确编码标识'}],
      },

      form: {
        specification: "",//规格
        // filePath: "",//文件
        templateId: "",//id
      },
      size: "",
      rules_: {
        filePath: [{required: true, trigger: 'blur', message: "请上传文件"}],
        // autoIncrementNum: [{required: true, trigger: 'change', message: "请输入自增次数"}],
        // transitionNumber: [{required: true, trigger: 'change', message: "请输入每行/列个数"}],
        // autoIncrement: [{required: true, trigger: 'change', message: "请输入自增值"}],
      },

      formList: {},
      canvasListAll: {},

      selected: {},

      fileList: [],
      dialogType: "open",
      autoView: false,

      addToAttr: {
        specification: this.size,
        type: "popAdd",
        autoDirection: "bottom",
        autoIncrementNum: 1,
        transitionNumber: 1,
        autoIncrement: 1,
        name: "",
        code: ""
      },

      //对pdf进行缩放处理，以 A4 为基础大小
      resize: {
        "A3": 0.71,
        "A4": 1,
        "A5": 1.42,
        "A6": 2,
      },
      errorMsg: ""
    }
  },
  computed: {
    size() {
      return this.formData.specification;
    },
    sizeObj() {
      let specification = this.deepCopy(this.specification);
      if (specification.length > 0) {
        let arr = specification.filter(i => i.name === this.size);
        if (arr.length > 0) {
          return arr[0].value ? arr[0].value.split("_").map(i => i * this.resize[this.size]) : [0, 0]
        }
        return [0, 0]
      }
      return [0, 0]
    }
  },
  methods: {
    blurCode(row) {
      let reg = /^[a-z][a-z0-9_]{1,29}$/;
      let flag = reg.test(row.code);
      if (!flag) {
        this.$message.warning("请输入正确的编码");
        row.code = "";
      }
    },
    refreshCanvas() {
      this.$refs["cc"].refresh_canvas();
    },
    setAttr(row) {
      Object.assign(row, {
        autoDirection: "bottom",
        autoIncrementNum: 1,
        transitionNumber: 1,
        autoIncrement: 1,
      })
    },
    handleRemove() {
      this.formData = {filePath: "", name: ""};
      this.formList[this.size] = {filePath: "", fileName: ""};
    },
    handleChange(file, fileList) {
      console.log(file)
      let formData = new FormData();
      formData.append("file", file.raw);
      this.showPdf = false;
      request({
        method: "post", url: "/api/file-api/mx-file/uploadpicture", data: formData,
        headers: {"Content-Type": "multipart/form-data"}
      }).then(res => {
        this.showPdf = true;
        this.formData.filePath = res.data.data;
        this.formData.fileName = file.name;
      })
      this.fileList = fileList;
    },
    removeItem(row) {
      this.canvasListAll[this.formData.specification] = this.canvasListAll[this.formData.specification].filter(i => i.SELF_OID !== row.SELF_OID)
      this.$refs["cc"].remove_item(row);
    },
    tableRowClassName({row}) {
      if (!!this.selected && Object.keys(this.selected).length > 0) {
        return row.SELF_OID === this.selected.target.SELF_OID ? "selected-row" : ""
      }
      return '';
    },
    checkCanvas(val) {
      this.autoView = false;
      this.showPdf = false;
      this.showPdf = true;
      this.formData = this.formList[val];
      this.fileList = [];
      if (this.formList[this.size].filePath) {
        this.fileList = [{filePath: this.formList[this.size].filePath, name: this.formList[this.size].fileName}]
      }
      this.$nextTick(() => {
        this.$refs["cc"].refresh_canvas();
      })
    },
    errorFun(error) {
      if (this.dialogType === "view") {
        return;
      }
      if (!this.formData.filePath) {
        this.$message.warning("请上传图片");
        return;
      }
      if (error === "limit") {
        this.$message.warning("只能选取1处签名区域");
      }
    },
    save() {
      this.errorMsg = "";
      this.$refs["formBase"].validate(f => {
        if (f) {
          let form = {...this.formDataBase};
          let coordinateList = [];
          let typeList = [];
          let rules = [];
          let reg = /^[a-z][a-z0-9_]{1,29}$/;

          for (const key in this.canvasListAll) {
            let data = this.canvasListAll[key];
            data.forEach(item => {
              let {name, code, specification} = item;
              if (!name || !code) {
                if (!typeList.includes(specification)) typeList.push(specification)
              }
              if (code && !reg.test(code)) {
                if (!rules.includes(specification)) rules.push(specification)
              }
              coordinateList.push({
                ...item, ...this.getFormData(key),
                x: item.x / this.resize[this.size],
                y: item.y / this.resize[this.size],
                width: item.width / this.resize[this.size],
                height: item.height / this.resize[this.size],
              })
            })
          }
          form.coordinateList = coordinateList;

          if (typeList.length > 0) {
            this.errorMsg = `请完整填写${typeList.join(",")}规格 坐标表格名称与编码`
            this.$message.warning(this.errorMsg);
            if (this.size !== typeList[0]) {
              this.size = typeList[0];
              this.checkCanvas(typeList[0])
            }
            return;
          }
          if (rules.length > 0) {
            this.errorMsg = `${rules.join(",")}规格 坐标表格编码格式错误`
            this.$message.warning(this.errorMsg);
            if (this.size !== rules[0]) {
              this.size = rules[0];
              this.checkCanvas(rules[0])
            }
            return;
          }
          let methods = this.dialogType === "open" ? "save" : "update";
          api[methods](form).then(() => {
            this.$message.success("保存成功");
            this.$emit('removeThisTabs');
            this.$emit('refresh');
          })
        }
      })
    },
    getFormData(key) {
      return this.formList[key]
    },
    open() {
      this.dialogType = "open";
      this.getPaperSize();
    },
    edit(row) {
      this.dialogType = "edit";
      this.getPaperSize(row);

    },
    view(row) {
      this.dialogType = "view";
      this.getPaperSize(row);
    },
    getDetails(row) {
      api.getDetail({oid: row.oid}).then(res => {
        let data = res.data.data;
        Object.assign(this.formDataBase, data)
        delete this.formDataBase.coordinateList;
        if (data.coordinateList && data.coordinateList.length > 0) {
          data.coordinateList.forEach(item => {
            let SELF_OID = this.getOnlyId();
            this.canvasListAll[item.specification].push({
              x: item.x * this.resize[this.size],
              y: item.y * this.resize[this.size],
              width: item.width * this.resize[this.size],
              height: item.height * this.resize[this.size],
              SELF_OID: SELF_OID,
              type: "popAdd",
              hasDynamic: item.hasDynamic,
              autoDirection: item.autoDirection,
              autoIncrementNum: item.autoIncrementNum,//自增次数
              transitionNumber: item.transitionNumber,//每行/列个数
              autoIncrement: item.autoIncrement,//自增值
              specification: item.specification,//自增值
              filePath: item.filePath,
              name: item.name || "",
              code: item.code || ""
            })

            this.formList[item.specification] = {
              filePath: item.filePath,
              fileName: item.fileName,
              specification: item.specification
            }

            this.formData = this.deepCopy(this.formList[this.specification[0].name]);
          })

          this.fileList = [{filePath: this.formList[this.size].filePath, name: this.formList[this.size].fileName}]
        }
        let key = setTimeout(() => {
          this.$refs["cc"].refresh_canvas();
          clearTimeout(key);
        }, 600)
      })
    },
    getPaperSize(row) {
      getDic("paper_size").then(res => {
        this.specification = res.data.data;
        this.size = this.specification[0].name;

        for (let i = 0; i < this.specification.length; i++) {
          let item = this.specification[i];
          let form = this.deepCopy(this.form)
          this.formList[item.name] = {...form, specification: item.name}

          this.$set(this.canvasListAll, item.name, []);
        }

        if (['view', 'edit'].includes(this.dialogType)) {
          this.getDetails(row);
        }
      })
    }
  },
  watch: {
    "formData.filePath": {
      handler(nv) {
        this.$nextTick(() => {
          this.$refs["cc"] && this.$refs["cc"].ms$set("disabledDraw", !nv);
        })
      },
      deep: true,
      immediate: false
    },
  }
}
</script>

<style scoped lang="scss">
.signatureTemplateManageTemp {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  flex-wrap: nowrap;

  .config {
    width: 44%;

    .el-input-number {
      width: 100%;
    }
  }

  .pdf_view {
    width: 54%;
    position: relative;
  }
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.5s;
}

.fade-enter,
.fade-leave-to {
  opacity: 0;
}
</style>

<style>
.el-table .selected-row {
  background: rgba(64, 158, 255, 0.3);
}
</style>
